﻿using System.IO;

namespace UtilZ.Dotnet.Ex.Communication.Net.BMQ
{
    /// <summary>
    /// BMQ数据消息基类
    /// </summary>
    public abstract class BMQDataMessageAbs : BMQMessageAbs, IBMQDataMessage
    {
        /****************************************************
         * BMQ订阅-请求消息结构
         * 字段   数据类型    大小(byte)  说明
         * Type   byte        1           消息类型
         * Topic  Int16       2           主题
         * Data   byte[]      变长        数据
         ****************************************************/

        /// <summary>
        /// BQM数据消息头大小
        /// </summary>
        protected const int BMQ_DATA_HEADER_SIZE = 3;

        private short _topic;
        /// <summary>
        /// 订阅主题
        /// </summary>
        public short Topic
        {
            get { return _topic; }
            set { _topic = value; }
        }


        /// <summary>
        /// 构造函数-解析
        /// </summary>
        /// <param name="messageType">BMQ消息类型</param>
        public BMQDataMessageAbs(byte messageType)
            : base(messageType)
        {

        }

        /// <summary>
        /// 构造函数-创建
        /// </summary>
        /// <param name="messageType">BMQ消息类型</param>
        /// <param name="topic">订阅主题</param>
        public BMQDataMessageAbs(byte messageType, short topic)
            : base(messageType)
        {
            this._topic = topic;
        }



        /// <summary>
        /// 将消息写入二进制buffer
        /// </summary>
        /// <param name="writer">消息写器</param>
        protected override void WriteMessage(BinaryWriter writer)
        {
            writer.Write(base._messageType);
            writer.Write(this._topic);
            this.WriteContent(writer);
        }

        /// <summary>
        /// 写消息内容到BinaryWriter
        /// </summary>
        /// <param name="writer">消息写器</param>
        protected abstract void WriteContent(BinaryWriter writer);




        /// <summary>
        /// 读取消息到对象
        /// </summary>
        /// <param name="reader">消息读取器</param>
        protected override void ReadMessage(BinaryReader reader)
        {
            byte messageType = reader.ReadByte();
            this._topic = reader.ReadInt16();
            int dataLength = (int)(reader.BaseStream.Length - reader.BaseStream.Position);
            this.ReadContent(reader, dataLength);
        }


        /// <summary>
        /// 读取消息内容
        /// </summary>
        /// <param name="reader">内容二进制数据</param>
        /// <param name="dataLength">数据字节数</param>
        protected abstract void ReadContent(BinaryReader reader, int dataLength);

    }
}
